<template>
  <div>
    <!-- form: 在 iOS 输入法中显示搜索按钮-->
    <!-- 搜索框 -->
    <form action="/">
      <van-search
        v-model.trim="keywords"
        background="#3296fa"
        class="search-inp"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isShowResult = false"
      />
    </form>
    <!-- 搜索历史/建议/结果 -->
    <!-- v-if/else-if/else -->
    <!-- <component is="组件名" /> -->
    <component
      :keywords="keywords"
      :is="componentName"
      @update-keywords="onSearch"
    />
  </div>
</template>

<script>
import SearchHistory from './components/SearchHistory.vue'
import SearchSuggestions from './components/SearchSuggestions.vue'
import SearchResult from './components/SearchResult.vue'

import { mapMutations, mapState } from 'vuex'
export default {
  components: {
    SearchHistory,
    SearchSuggestions,
    SearchResult
  },
  data() {
    return {
      keywords: '',
      isShowResult: false // 记录了是否触发了搜索事件
    }
  },
  computed: {
    ...mapState(['histories']),
    componentName() {
      // 1. 搜索框没有实际内容的时候 渲染搜索历史
      if (this.keywords === '') {
        return 'SearchHistory'
      }

      // keywords 一定有值
      //  - 要么渲染搜索建议, 要么渲染搜索结果
      if (this.isShowResult) {
        return 'SearchResult'
      }

      // 代码能走到这? 不渲染搜索历史和搜索结果了, 此时渲染搜索建议

      return 'SearchSuggestions'
    }
  },
  methods: {
    ...mapMutations(['SET_HISTORIES']),
    // val: 搜索框显示的值
    onSearch(val) {
      // 1. 更新keywords
      this.keywords = val

      // 2. 存到vuex
      let newHistories = [this.keywords, ...this.histories]
      // 3. 去重
      //  - new Set
      newHistories = [...new Set(newHistories)]

      this.SET_HISTORIES(newHistories)
      // 4. 展示搜索结果
      this.isShowResult = true
    },
    onCancel(val) {
      // 触发取消, 先清空keywords, 再触发onCancel
      if (this.keywords === '') {
        // 返回上一页
        this.$router.back()
        // this.$router.go(-1)
      } else {
        this.keywords = ''
      }
    }
  }
}
</script>

<style scoped lang="less">
.search-inp {
  .van-search__action {
    color: #fff;
  }
}
</style>
